<template>
  <div>
    <el-form>
      <el-form-item label="SPU名称" label-width="80">
        <el-input
          v-model="spuData.spuName"
          placeholder="请输入SPU名称"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="品牌" label-width="80">
        <el-select
          v-model="spuData.tmId"
          class="m-2"
          placeholder="请选择品牌分类"
        >
          <el-option
            v-for="i in trademarkList"
            :key="i.id"
            :label="i.tmName"
            :value="i.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="描述" label-width="80">
        <el-input
          v-model="spuData.description"
          type="textarea"
          placeholder="请输入SPU描述"
        />
      </el-form-item>
      <el-form-item label="照片" label-width="80">
        <el-upload
          v-model:file-list="spuImageListData"
          :action="setting.imgUploadUrl"
          list-type="picture-card"
          :on-remove="handleRemove"
          :on-success="uploadDone"
          :on-error="uploadError"
          :on-preview="handlePictureCardPreview"
          :before-upload="beforeAvatarUpload"
        >
          <el-icon>
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="销售属性" label-width="80">
        <el-select
          v-model="waitAddAttr"
          class="m-2"
          :placeholder="`您还可以选择${unSelectSaleAttr.length}个`"
        >
          <el-option
            v-for="i in unSelectSaleAttr"
            :key="i.id"
            :label="i.name"
            :value="`${i.id}:${i.name}`"
          />
        </el-select>
        <el-button
          icon="Plus"
          type="primary"
          @click="addAttr"
          :disabled="!waitAddAttr"
          >添加销售属性</el-button
        >
        <el-table
          border
          style="margin-top: 10px"
          :data="spuData.spuSaleAttrList"
        >
          <el-table-column
            label="序号"
            type="index"
            width="80"
          ></el-table-column>
          <el-table-column
            label="属性名"
            width="100"
            prop="saleAttrName"
          ></el-table-column>
          <el-table-column label="属性值">
            <template #="{ row, $index }">
              <el-tag
                closable
                @close="deleteAttrValue($index, index)"
                style="margin: 5px"
                v-for="(i, index) in row.spuSaleAttrValueList"
                :key="i.id"
                >{{ i.saleAttrValueName }}</el-tag
              >
              <el-input
                :ref="(vc: any) => (row.vcRef = vc)"
                @blur="toLook(row)"
                v-if="row.isEdit == true"
                v-model="row.attrValue"
                style="width: 80px"
                size="small"
                type="text"
                placeholder="请输入属性值"
              ></el-input>
              <el-button
                v-else
                type="success"
                size="small"
                icon="Plus"
                @click="toEdit(row)"
              ></el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #="{ $index }">
              <el-button
                type="danger"
                size="small"
                icon="Delete"
                @click="deleteAttr($index)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <el-button
      :disabled="spuData.spuSaleAttrList.length <= 0"
      type="primary"
      @click="submitSpu"
      >提交</el-button
    >
    <el-button @click="cancel">取消</el-button>
    <!-- <el-button @click="console.log(spuData)">查看当前SPU数据</el-button> -->

    <el-dialog v-model="dialogVisible">
      <img style="width: 100%" :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, nextTick, reactive, ref } from "vue";
import type { SpuObj } from "@/api/product/spu/type";
import setting from "@/setting";
import useCategoryStore from "@/store/modules/category";
import { ElNotification } from "element-plus";
//引入修改要用到的接口
import { spuImageList, reqspuSaleAttrList } from "@/api/product/sku";
import { reqGetTrademarkList } from "@/api/product/trademark";
import {
  baseSaleAttrList,
  updateSpuInfo,
  saveSpuInfo,
} from "@/api/product/spu";

const $emit = defineProps(["returnVc", "spuFormMode"]);
let categoryStore = useCategoryStore();
let spuData = reactive<SpuObj>({
  spuName: "",
  description: "",
  tmId: null,
  category3Id: categoryStore.chooseCategory[2],
  spuImageList: [],
  spuSaleAttrList: [],
});
let waitAddAttr = ref<any>(null);

//当点击添加销售属性
const addAttr = () => {
  let [baseSaleAttrId, saleAttrName] = waitAddAttr.value.split(":");
  let newAttr = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: [],
  };
  spuData.spuSaleAttrList.push(newAttr);
  waitAddAttr.value = null;
};

//图片上传相关方法
let fileList = ref<any>([]);
let dialogImageUrl = ref<any>("");
let dialogVisible = ref<any>(false);
const handleRemove = (uploadFile: any, uploadFiles: any) => {
  console.log("删除图片", uploadFile, uploadFiles, fileList.value);
};
const handlePictureCardPreview = (uploadFile: any) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
const uploadDone = (result: any) => {
  if (result.code == 200) {
    ElNotification({
      type: "success",
      title: result.message,
    });
  } else {
    ElNotification({
      type: "error",
      title: result.message,
    });
  }
};
const uploadError = (error: any) => {
  ElNotification({
    type: "error",
    title: error,
  });
};
//上传前的校验，借鉴于element官网
const beforeAvatarUpload = (rawFile: any) => {
  if (rawFile.type == "image/jpeg" || rawFile.type == "image/png") {
    if (rawFile.size / 1024 / 1024 < 2) {
      return true;
    } else {
      ElNotification.error("图片大小必须小于2mb");
      return false;
    }
  } else {
    ElNotification.error("图片格式只能是jpg或png格式");
    return false;
  }
};

//取消并返回父组件
const cancel = () => {
  $emit.returnVc();
};

//封装获取要修改的数据的方法并暴露给父组件，等父组件通知调用
let trademarkList = ref<any>([]);
let AllSaleAttrList = ref<any>([]);
let spuImageListData = ref<any>([]);
const getSpuData = async (spuRow: any) => {
  try {
    spuRow.spuSaleAttrList = []; //由于获取到的该数据为null会导致报错，这里先处理一下数据
    Object.assign(spuData, JSON.parse(JSON.stringify(spuRow)));

    trademarkList.value = (await reqGetTrademarkList()).data; //所有品牌
    AllSaleAttrList.value = (await baseSaleAttrList()).data; //所有销售属性
    //已有的图片,转换成elment需要的格式
    spuImageListData.value = (await spuImageList(spuRow.id)).data.map(
      (item: any) => {
        return {
          name: item.imgName,
          url: item.imgUrl,
        };
      },
    );
    spuData.spuSaleAttrList = (await reqspuSaleAttrList(spuRow.id)).data; //已有的销售属性
  } catch (error) {
    console.log(error);
  }
};

// 如果是添加SPU，则先清空初始数据，获取必要的数据
const resetSpuData = async () => {
  Object.assign(
    spuData,
    JSON.parse(
      JSON.stringify({
        spuName: "",
        description: "",
        tmId: null,
        category3Id: categoryStore.chooseCategory[2],
        spuImageList: [],
        spuSaleAttrList: [],
      }),
    ),
  );
  delete spuData.id;
  waitAddAttr.value = null;
  spuImageListData.value = [];
  trademarkList.value = (await reqGetTrademarkList()).data; //所有品牌
  AllSaleAttrList.value = (await baseSaleAttrList()).data; //所有销售属性
};
defineExpose({ getSpuData, resetSpuData });

//提交表单
const submitSpu = async () => {
  //简单的校验表单，实际项目建议使用form表单的校验规则
  if (spuData.spuName == "" || spuData.tmId == null) {
    ElNotification.error("名称和品牌为必填项");
    return;
  }
  //将图片对象格式转换回接口所需要的格式
  spuData.spuImageList = spuImageListData.value.map((item: any) => {
    return {
      imgUrl: (item.response && item.response.data) || item.url,
      imgName: item.name,
    };
  });
  //数据收集完毕，开始发送修改或添加请求
  if ($emit.spuFormMode == 1) {
    let result = await saveSpuInfo(spuData);
    if (result.code == 200) {
      ElNotification.success("添加成功");
      cancel();
    }
  } else if ($emit.spuFormMode == 2) {
    let result = await updateSpuInfo(spuData);
    if (result.code == 200) {
      ElNotification.success("更新成功");
      cancel();
    }
  }
};
//删除属性
const deleteAttr = (idx: number) => {
  spuData.spuSaleAttrList.splice(idx, 1);
};
const deleteAttrValue = (attrIdx: number, attrValueIdx: number) => {
  spuData.spuSaleAttrList[attrIdx].spuSaleAttrValueList.splice(attrValueIdx, 1);
};
// 计算spu还未拥有的销售属性（全部销售属性除去已有销售属性）
let unSelectSaleAttr = computed(() => {
  return AllSaleAttrList.value.filter((item: any) => {
    return spuData.spuSaleAttrList.every((item2: any) => {
      return item.name != item2.saleAttrName;
    });
  });
});

//切换编辑模式
const toEdit = (row: any) => {
  row.isEdit = true;
  row.attrValue = "";
  nextTick(() => {
    row.vcRef.focus();
  });
};
//切换按钮模式，并存入数据，且不能重复和为空
const toLook = (row: any) => {
  if (row.attrValue != "") {
    let repeat = false;
    row.spuSaleAttrValueList.forEach((i: any) => {
      if (i.saleAttrValueName == row.attrValue) {
        repeat = true;
        return;
      }
    });
    if (!repeat) {
      row.spuSaleAttrValueList.push({
        baseSaleAttrId: row.baseSaleAttrId,
        saleAttrValueName: row.attrValue,
      });
    } else {
      ElNotification.error("属性值不能重复");
    }
  }
  row.isEdit = false;
  row.attrValue = "";
};
</script>

<style scoped></style>
